package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void addOrderSettingList(List<OrderSetting> orderSettingList) {
        if (orderSettingList!=null &&  orderSettingList.size()>0){
            for (OrderSetting orderSetting : orderSettingList) {
                saveOrEdit(orderSetting);
            }
        }
    }

    @Override
    public List<OrderSetting> findByMonth(String date) throws ParseException {
        //2020-02-01
        String thisMonthFirstDay = date + "-01";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date firstDay = sdf1.parse(thisMonthFirstDay);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(firstDay);
        calendar.add(Calendar.MONTH,1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date lastDay = calendar.getTime();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String thisMonthLastDay = sdf2.format(lastDay);
        return orderSettingDao.findByMonth(thisMonthFirstDay,thisMonthLastDay);
    }

    @Transactional
    public void saveOrEdit(OrderSetting orderSetting){
        OrderSetting orderSettingDb = orderSettingDao.findOrderSettingByDate(orderSetting.getOrderDate());
        if(orderSettingDb==null){
            orderSettingDao.add(orderSetting);
        }else{
           if(orderSettingDb.getReservations()>orderSetting.getNumber()){
               throw new BusinessRuntimeException("已预约人数不能大于可预约人数!!!");
           }else{
               orderSettingDao.edit(orderSetting);
           }
        }
    }
}
